package com.handpay.zztong.hp.swiper.widget;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.handpay.framework.swiper.landi.AipSharedPreferences;
import com.handpay.zztong.hp.swiper.adpater.SwiperBluetoothAdapter;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.ZZTApplication;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.swiper.model.SwiperBluetoothDeviceSelectInfo;

import java.util.ArrayList;
import java.util.List;

public class SwiperBluetoothSelectView extends LinearLayout {

	public static String EXTRA_DEVICE_ADDRESS = "address";
	public static String EXTRA_DEVICE_INFO = "name";
	// 用于过滤只显示符合条件名字的蓝牙设备。
	// 暂时是名称里包含这些字符。以后如果有需要可以做成正则过滤
	public static String NAME_FILTER = "name_filter";
	public static String DEVICE_NAME = "device_name";
	private String mNameFilter = ZZTConstant.DEFAULT_NAME_FILTER;

	// 成员域。用于显示的
	private SwiperBluetoothAdapter mSwiperBluetoothAdapter;
	// 用于搜素蓝牙设备的
	private BluetoothAdapter mBluetoothAdapter;
	// 3、31新增
	private List<BluetoothDevice> listBD = new ArrayList<BluetoothDevice>();

	private SwiperBluetoothDeviceSelectInfo mSwiperBluetoothDeviceInfo;
	private String mDeviceName;

	private Context mContext;

	private OnSwiperBluetoothSelectOnItemClickListenter mItemClickListener;

	public interface OnSwiperBluetoothSelectOnItemClickListenter {
		void onSelectClick(String devicename, String deviceid,  String deviceInfo);

		void OnCancelClick();

		void OnDiscoverComplete();
	}

	public void setmItemClickListener(OnSwiperBluetoothSelectOnItemClickListenter mItemClickListener) {
		this.mItemClickListener = mItemClickListener;
	}

	public SwiperBluetoothSelectView(Context context, String mNameFilter, String mDeviceName) {
		this(context);
		this.mDeviceName = mDeviceName;
		this.mNameFilter = mNameFilter;
		mContext = context;
		View view = LayoutInflater.from(context).inflate(R.layout.layout_swiper_bluetooth_select, null);
		initView(view);
		SwiperBluetoothSelectView.this.addView(view, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
	}

	public SwiperBluetoothSelectView(Context context) {
		super(context);
	}

	private void initView(View view) {
		// 设置已配队设备列表
		mSwiperBluetoothAdapter = new SwiperBluetoothAdapter(mContext, mNameFilter);
		mSwiperBluetoothAdapter.setDeviceName(mDeviceName);
		ListView pairedListView = (ListView) view.findViewById(R.id.paired_devices);
		pairedListView.setAdapter(mSwiperBluetoothAdapter);
		pairedListView.setOnItemClickListener(mDeviceClickListener);
		view.findViewById(R.id.button_cancel).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mItemClickListener != null) {
					unregisterBluetoothReceiver();
					mItemClickListener.OnCancelClick();
				}
			}
		});
	}

	public void initData(){
		// 注册接收查找到设备action接收器
		IntentFilter mBroadcastReceiverFilter = new IntentFilter();
		mBroadcastReceiverFilter.addAction(BluetoothDevice.ACTION_FOUND);
		mBroadcastReceiverFilter.addAction(android.bluetooth.BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		mContext.registerReceiver(mReceiver, mBroadcastReceiverFilter);
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter.isEnabled()) {
			doDiscovery();
		} else {
			Toast.makeText(mContext, mContext.getString(R.string.please_open_bluetooth), Toast.LENGTH_SHORT).show();
			mItemClickListener.OnCancelClick();
		}
	}

	/**
	 * 开始服务和设备查找
	 */
	private void doDiscovery() {

		// 关闭再进行的服务查找
		if (mBluetoothAdapter.isDiscovering()) {
			mBluetoothAdapter.cancelDiscovery();
		}
		// 并重新开始
		HPLog.i(HPLog.YL_TAG,"开始服务和设备查找");
		mBluetoothAdapter.startDiscovery();
	}

	// 选择设备响应函数
	private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
			mSwiperBluetoothDeviceInfo = mSwiperBluetoothAdapter.getDeviceInfo(arg2);
			AipSharedPreferences.getInstance(mContext).setBluetoothDeviceInfo(mSwiperBluetoothDeviceInfo);
			// AipSharedPreferences.SelectLastDevice lastDevice = new
			// AipSharedPreferences.SelectLastDevice();
			// lastDevice.selectType =
			// AipSharedPreferences.DEVICE_TYPE_BLUETOOTH;
			// lastDevice.selectIndex = arg2;
			// AipSharedPreferences.getInstance(mContext).setSelectLastDevice(lastDevice);
			if (ZZTConstant.ME368_NAME_FILTER.equals(mNameFilter)) {
				ZZTApplication.getInstance().bdDevice = listBD.get(arg2);
			} else if (ZZTConstant.M188_NAME_FILTER.equals(mNameFilter) || ZZTConstant.M198_NAME_FILTER.equals(mNameFilter)) {
				ZZTApplication.getInstance().bdDevice = listBD.get(arg2);
			} else if (ZZTConstant.M1218_NAME_FILTER.equals(mNameFilter)) {
				ZZTApplication.getInstance().bdDevice = listBD.get(arg2);
			}
			if (mItemClickListener != null) {
				unregisterBluetoothReceiver();
				mItemClickListener.onSelectClick(mSwiperBluetoothDeviceInfo.getName(), mSwiperBluetoothDeviceInfo.getIdentifier(), mSwiperBluetoothDeviceInfo.getIdentifier());

			}
		}
	};
	// 查找到设备和搜索完成action监听器
	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			HPLog.i(HPLog.YL_TAG, "action:" + action);
			HPLog.i(HPLog.YL_TAG, "设备过滤:" + mNameFilter);

			// 查找到设备action
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				// 得到蓝牙设备
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			
				String deviceName = device.getName();
				HPLog.i(HPLog.YL_TAG, "找到设备名:" + deviceName);
				HPLog.i(HPLog.YL_TAG, "设备地址:" + 	device.getAddress());

				if (TextUtils.isEmpty(deviceName)) {
					deviceName = mContext.getString(R.string.unknown_device);
				}
				// 过滤蓝牙设备.有名字，且不包含特定字符的设备，过滤掉
				if (!deviceName.contains(mNameFilter)) {
					return;
				}
				// 3、31新增
				// 这里是m368可以连接的设备中去掉4.0
				if (!device.getName().endsWith("LE")) {
					listBD.add(device);
				}
				SwiperBluetoothDeviceSelectInfo bludeDeviceInfo = new SwiperBluetoothDeviceSelectInfo();
				// 从这里获取的设备信息一定为蓝牙
//				deviceInfo.setDevChannel(CommunicationManagerBase.DeviceCommunicationChannel.BLUETOOTH);
				bludeDeviceInfo.setIdentifier(device.getAddress());
				if (!device.getName().endsWith("LE")) {
					// 选择设备页面去掉m368 4.0
					bludeDeviceInfo.setName(device.getName());
				}
//				SwiperBluetootnDeviceInfo deviceInfo = new SwiperBluetootnDeviceInfo();
//deviceInfo.setSelectType(SwiperBluetootnDeviceInfo.DEVICE_TYPE_BLUETOOTH);
//				deviceInfo.setIdentifier(device.getAddress());
//				deviceInfo.setName(deviceName);
				discoverOneDevice(bludeDeviceInfo);
				// 搜索完成action
			} else if (android.bluetooth.BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
				if (mSwiperBluetoothAdapter.getCount() == 0){
					mItemClickListener.OnDiscoverComplete();
				}
				unregisterBluetoothReceiver();
			}
		}
	};



	public void discoverOneDevice(SwiperBluetoothDeviceSelectInfo deviceInfo) {
		if (deviceInfo != null && deviceInfo.getName() != null) {
			HPLog.i("discoverOneDevice", deviceInfo.getName());
			boolean noMatch = false;
			for (int i = 0; i < mSwiperBluetoothAdapter.getCount(); i++) {
				SwiperBluetoothDeviceSelectInfo device = mSwiperBluetoothAdapter.getDeviceInfo(i);
				if (device.getIdentifier().equals(deviceInfo.getIdentifier()) && device.getName().equals(deviceInfo.getName())) {
					noMatch = true;
				}
			}
			// 去重
			if (!noMatch) {
				mSwiperBluetoothAdapter.addDevice(deviceInfo);
			}
		}
	}

	public void unregisterBluetoothReceiver() {
		HPLog.i(HPLog.YL_TAG,"注销蓝牙请求");
		if (mReceiver !=null){
			mContext.unregisterReceiver(mReceiver);
		}
		if (mBluetoothAdapter != null) {
			mBluetoothAdapter.cancelDiscovery();
		}
		if (mSwiperBluetoothAdapter != null) {
			mSwiperBluetoothAdapter.clear();
		}
	}
}
